package com.ubing.boot.notesforjava.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ubing.boot.notesforjava.annotation.JwtExceptions;
import com.ubing.boot.notesforjava.response.Response;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import static com.ubing.boot.notesforjava.utils.JwtUtils.generalKey;

/**
 * @author ubing
 * @date 2023/2/17/ 14:51
 */
//@Component
@JwtExceptions
public class CheckTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = request.getHeader("token");
        if (token == null) {
            // 没有传 token; 提示请先登录
            doResponse(response,Response.tokenError("请先登录"));
            return false;
        }
        try {
            // 获取 解析器parser; 验证token
            JwtParser parser = Jwts.parser();
            // 解析token 的 SigningKey 必须和生成的token时设置的密码一致
            parser.setSigningKey(generalKey());
            // 如果 token正确(密码正确, 有效期内) 则正常执行, 否则抛出 异常
            Jws<Claims> claimsJws = parser.parseClaimsJws(token);
            String requestURI = request.getRequestURI().intern();
            if(requestURI=="/userInfo/checkToken"){
                request.setAttribute("id",claimsJws.getBody().getId());
                request.setAttribute("userName",claimsJws.getBody().getSubject());
            }
        }catch (Exception e){
            //将异常分发到/error/exception控制器
            request.setAttribute("filter.error",e);
            request.getRequestDispatcher("/error/exception").forward(request, response);
        }

        return true; // 放行;
    }
    private void doResponse(HttpServletResponse response,Response res) throws IOException {
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            PrintWriter out = response.getWriter();
            out.print(res);
            out.flush();
            out.close();
        }
}